'use strict';

const Service = require('egg').Service;

class ArticleService extends Service {


  /**
   *获取列表 带用户搜索记录
   * @param {载荷} payload
   * @return {Promise<>}
   */
  async getArticle(payload) {
    const { app, ctx } = this;
    const Op = app.Sequelize.Op;
    const { pageNum, pageSize, category_id, user_id, status, keywords, begin_pubdate, end_pubdate } = payload;
		console.log('payload============>',payload);
    const where = {};
    if (category_id) { where.category_id = category_id; }
    if (user_id) { where.user_id = user_id; }
    if (status) { where.status = status; }
    if (keywords) {
      where.title = { [Op.like]: `%${keywords}%` };
      // 当用户搜索文章时 调用新增用户搜索记录
      await ctx.service.m.search.create(payload);
    }
    if (begin_pubdate && end_pubdate) {
      where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
    }// 查询这个字段-xx之间  }
    // notBetween
    try {
      const { count, rows } = await app.model.Article.findAndCountAll({
        where,
        // attributes: [ 'id', 'title', 'createdAt', 'category_id', 'status' ], // 只查哪些字段
        order: [[ 'createdAt', 'desc' ]], // 根据创建时间倒序排序
        include: [
          {
            model: this.app.model.ArticleCategory,
            as: 'category',
            attributes: [ 'name' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'nickname', 'avatar','introduce' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
        ],
        offset: (pageNum - 1) * pageSize,
        limit: pageSize * 1,
      });
      console.log('rows', rows);
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }
  // // 获取热门文章
  // async getHotArticle(payload) {
  //   const { app } = this;
  //   const Op = app.Sequelize.Op;
  //   const { pageNum, pageSize, user_id, keywords, begin_pubdate, end_pubdate } = payload;
  //   const where = {};
  //   if (user_id) { where.user_id = user_id; }
  //   if (keywords) { where.keywords = { [Op.like]: `%${keywords}%` }; }
  //   if (begin_pubdate && end_pubdate) {
  //     where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
  //   }// 查询这个字段-xx之间  }
  //   // notBetween
  //   try {
  //     const { count, rows } = await app.model.Article.findAndCountAll({
  //       where,
  //       order: [[ 'read_count', 'DESC' ]], // 根据搜索量倒序排序
  //       offset: (pageNum - 1) * pageSize,
  //       limit: pageSize * 1,
  //     });
  //     return {
  //       pageNum,
  //       pageSize,
  //       total: count,
  //       list: rows,
  //     };
  //   } catch (error) {
  //     console.error(error);
  //     return null;
  //   }
  // }
  // 获取用户浏览文章历史记录 根据用户id
  async getUserArticleViewHistory(user_id, payload) {
    console.log(user_id, payload);
    const { app } = this;
    const { pageNum, pageSize } = payload;
    const { count, rows } = await app.model.ArticleView.findAndCountAll({
      where: { user_id },
      order: [[ 'updatedAt', 'desc' ]], // 根据更新时间倒序排序
      include: {
        model: app.model.Article,
        as: 'article',
        include: [
          {
            model: this.app.model.ArticleCategory,
            as: 'category',
            attributes: [ 'name' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'nickname', 'avatar','introduce'],  // 只显示哪些字段
          },
        ],
      },
      offset: (pageNum - 1) * pageSize,
      limit: pageSize * 1,
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
  // 根据文章id获取文章信息
  async getArticleById(id) {
    const { app, ctx } = this;
    const res = await app.model.Article.findOne(
      {
        where: { id },
        include: {
          model: this.app.model.User,
          as: 'user',
          attributes: [ 'nickname', 'avatar','introduce'], // 只显示哪些字段
        // through: { attributes: [] }, // 排除中间表
        },
      });
    if (res.dataValues) {
      // 查询成功的话 就让阅读量加1
      await app.model.Article.increment('read_count', { where: { id } });
      // 获取文章详情信息成功的话就新增一条用户查看 浏览记录
      await ctx.service.m.articleView.createUserView(id);
    }
    return res.dataValues;
  }
  // // 新增用户举报文章
  // async addReport(payload) {
  //   const { app } = this;
  //   const err = {};
  //   const { article_id, user_id } = payload;
  //   const isData = await app.model.ArticleReport.findOne({ where: { user_id, article_id } });
  //   if (isData) {
  //     err.msg = '您已经举报过啦，工作人员已经加速审核您的举报中...';
  //     console.log(err);
  //     return err;
  //   }
  //   return await app.model.ArticleReport.create(payload);
  // }
  // // 删除举报的文章 可批量删除
  // async destroyReport(payload) {
  //   const { app } = this;
  //   return await app.model.ArticleReport.destroy({ where: { id: payload.ids }, force: true });
  // }
  /**
   *获取举报列表
   * @param {载荷} payload
   * @return {Promise<>}
   */
  async getReportList(payload) {
    const { app } = this;
    const Op = app.Sequelize.Op;
    const { pageNum, pageSize, type, user_id, article_id, status, keywords, begin_pubdate, end_pubdate } = payload;
    const where = {};
    if (type) { where.type = type; }
    if (user_id) { where.user_id = user_id; }
    if (article_id) { where.article_id = article_id; }
    if (status) { where.status = status; }
    if (keywords) { where.remark = { [Op.like]: `%${keywords}%` }; }
    if (begin_pubdate && end_pubdate) {
      where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
    }// 查询这个字段-xx之间  }
    // notBetween
    try {
      const { count, rows } = await app.model.ArticleReport.findAndCountAll({
        where,
        attributes: { exclude: [ 'deletedAt', 'updatedAt' ] }, // 不显示哪些字段
        order: [[ 'createdAt', 'desc' ]], // 根据创建时间倒序排序
        include: [
          {
            model: this.app.model.Article,
            as: 'article',
            attributes: [ 'title' ], // 只显示哪些字段
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'user_name' ], // 只显示哪些字段
          },
        ],
        offset: (pageNum - 1) * pageSize,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }


  // 对文章点赞
  async addArticleLiking(payload) {
    const { app, ctx } = this;
    const { article_id } = payload;
    const user_id = ctx.state.user.id;
    const transaction = await app.model.transaction();
    const isData = await app.model.ArticleLiking.findOne({ where: { user_id, article_id } });
    if (isData) {
      const err = {};
      err.msg = '您已点过赞啦';
      return err;
    }
    const res = await app.model.ArticleLiking.create({ user_id, article_id }, transaction);
    if (res.dataValues) {
      // 点赞成功后 文章点赞总数自增加1
      await app.model.Article.increment('like_count', { where: { id: article_id } });
      await transaction.commit();
      return true;
    }
    await transaction.rollback();
    return false;
  }

  // 获取用户点赞的文章列表 根据用户id
  async getUserLikingList(user_id, payload) {
    const { app } = this;
    const { pageNum, pageSize } = payload;
    const { count, rows } = await app.model.ArticleLiking.findAndCountAll({
      where: { user_id },
      order: [
        [ 'createdAt', 'desc' ],
      ],
      include: {
        model: app.model.Article,
        as: 'article',
        include: [
          {
            model: this.app.model.ArticleCategory,
            as: 'category',
            attributes: [ 'name' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
          {
            model: this.app.model.User,
            as: 'user',
             attributes: [ 'nickname' ,'introduce','avatar'],// 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
        ],
      },
      offset: (pageNum - 1) * pageSize,
      limit: pageSize * 1,
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  // 对文章取消点赞
  async destroyArticleLiking(article_id) {
    const { app, ctx } = this;
    const user_id = ctx.state.user.id;
    const transaction = await app.model.transaction();
    const res = await app.model.ArticleLiking.destroy({ where: { article_id, user_id }, force: true, transaction });
    if (res === 1) {
      await app.model.Article.decrement('like_count', { where: { id: article_id } });
      await transaction.commit();
      return true;
    }
    await transaction.rollback();
    return false;
  }
  // 根据文章id获取点赞信息 根据文章id判断是否已点赞
  async articleLikingById(article_id) {
    const { app, ctx } = this;
    const user_id = ctx.state.user.id;
    const isData = await app.model.ArticleLiking.findOne({ where: { user_id, article_id } });
    return isData;
  }

  // 收藏文章
  async addCollect(payload) {
    const { app, ctx } = this;
    const { article_id } = payload;
    const user_id = ctx.state.user.id;
    const transaction = await app.model.transaction();
    const isData = await app.model.ArticleCollect.findOne({ where: { user_id, article_id } });
    if (isData) {
      const err = {};
      err.msg = '您已收藏过啦';
      return err;
    }
    const res = await app.model.ArticleCollect.create({ user_id, article_id }, transaction);
    if (res.dataValues) {
      await transaction.commit();
      return res;
    }
    await transaction.rollback();
    return false;
  }

  // 获取用户收藏文章列表 根据用户id
  async getUserCollectList(user_id, payload) {
    const { app } = this;
    const { pageNum, pageSize } = payload;
    const { count, rows } = await app.model.ArticleCollect.findAndCountAll({
      where: { user_id },
      order: [
        [ 'createdAt', 'desc' ],
      ],
      include: {
        model: app.model.Article,
        as: 'article',
        include: [
          {
            model: this.app.model.ArticleCategory,
            as: 'category',
            attributes: [ 'name' ], // 只显示哪些字段
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'nickname' ,'introduce','avatar'], // 只显示哪些字段
          },
        ],
      },
      offset: (pageNum - 1) * pageSize,
      limit: pageSize * 1,
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  //  取消收藏文章
  async destroyCollect(article_id) {
    const { app, ctx } = this;
    const user_id = ctx.state.user.id;
    const transaction = await app.model.transaction();
    const res = await app.model.ArticleCollect.destroy({ where: { article_id, user_id }, force: true, transaction });
    if (res === 1) {
      await transaction.commit();
      return true;
    }
    await transaction.rollback();
    return false;
  }

  // 根据文章id判断是否已收藏文章
  async CollectById(article_id) {
    const { app, ctx } = this;
    const user_id = ctx.state.user.id;
    const isData = await app.model.ArticleCollect.findOne({ where: { user_id, article_id } });
    return isData;
  }


}

module.exports = ArticleService;
